package com.htkj.demo

import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.webkit.CookieManager
import android.webkit.JavascriptInterface
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import java.io.IOException
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress


class MyWebView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : WebView(context, attrs) {
    var datagramSocket:DatagramSocket?=null
    var mIP:String="192.168.8.100"
    init {
        this.setLayerType(View.LAYER_TYPE_HARDWARE,  null); // 硬件加速层


        val webSettings = getSettings();
//如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);

//支持插件
        webSettings.setPluginState(WebSettings.PluginState.OFF);
//设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
//缩放操作
        webSettings.setSupportZoom(false); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(false); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        //   webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        webSettings.setAllowContentAccess(true);
        webSettings.javaScriptEnabled=true;
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);   //开启 database storage API 功能
//        webSettings.setAppCacheEnabled(true);//开启 Application Caches 功能
//        webSettings.setAppCacheMaxSize(1024 * 1024 * 8);// 实现8倍缓存
        webSettings.setMediaPlaybackRequiresUserGesture(false);  // 允许自动播放（部分版本有效）

        val appCachePath = context.cacheDir.absolutePath
//        webSettings.setAppCachePath(appCachePath)
        //  webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webSettings.setTextZoom(100)

        if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            CookieManager.getInstance().setAcceptThirdPartyCookies(this,true);
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        setWebViewClient(object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                Log.e("----","$url")
                view?.loadUrl(url!!)
                return false
            }
        });
        addJavascriptInterface(object :JsJavaBridge{
            @JavascriptInterface
            override fun sendUdpMsg(msg:String) {
            }
            @JavascriptInterface
            override fun setLanguage(language: String?) {

            }



        }, "android")



    }

    /**
     * 发送消息
     * @param data
     * @param serverAddress
     * @param port
     * @throws IOException
     */
     fun sendMessage(data: String, host:String) {
//        var encrypt=AESCBCUtil.encrypt(data)
//        if(encrypt.isNullOrEmpty()){ return}
//        post {
//            evaluateJavascript("window.app.switchType('" + 1 + "')"){ it->
//                Log.e("11111111","---1---"+it)//host
//            };
//
//            Log.e("11111111","发送完毕")//host
//        }

//        this.evaluateJavascript("window.app.switchType('1')", null);
        ThreadPoolUtlis.asyn {
            try {
                val datagramPacket = DatagramPacket(
                    data.toByteArray(),
                    data.length,
                    InetAddress.getByName(host),
                    18999//18777//
                )
                Log.e("11111111",datagramPacket.address.hostAddress)//host
                if (datagramSocket == null) {
                    datagramSocket = DatagramSocket()
                }
                datagramSocket?.send(datagramPacket)
            } catch (e: Exception) {
                e.printStackTrace()
                Log.e("11111111",e.toString())
            }
        }

    }

    fun sendH5(message:String){
        post {
            evaluateJavascript("window.app.switchType('" + message + "')"){ it->
                Log.e("11111111","---1---"+it)//host
            };
        }

    }
}